// 引用各模块路由
const userRouter = require('./src/router/userRouter')
const blogRouter = require('./src/router/blogRouter')
const querystring = require('querystring')
const getPostData = require('./src/utils/getPostData')

const serveHandle = async (req, res) => {
  // 设置返回格式为JSON
  res.setHeader('Content-Type', 'application/json')
  // 解析url 和 解析get参数
  req.path = req.url.split('?')[0]
  req.query = querystring.parse(req.url.split('?')[1])

  // 解析post参数
  req.body = await getPostData(req)

  let isExitBlog = blogRouter(req, res)
  console.log(isExitBlog, '--- isExitBlog ---')

  if (isExitBlog) {
    res.end(JSON.stringify(isExitBlog))
    return
  }

  let isExitUser = userRouter(req, res)
  if (isExitUser) {
    res.end(JSON.stringify(isExitUser))
    return
  }
  res.end(JSON.stringify({ message: '404 Not Found' }))
}

module.exports = serveHandle
